<script lang="ts" setup>

import {onMounted, ref} from 'vue'
import {deleteBook, getBookPage, getCategories, saveBook, upBook} from '@/api/admin'
import {Plus, Upload} from '@element-plus/icons-vue'
//封面图片上传成功回调函数
import type {UploadProps} from 'element-plus'
import {ElMessage} from "element-plus";
//新增图书
import {adminTokenStore} from '@/stores/adminToken'

const tableData = ref([])

// 日期格式化
const formatPublishDate = (row: any) => {
  const date = new Date(row.publishDate);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}

const getPageUsersFileData = ref({
  pageNumber: "1",
  pageSize: "10",
  title: "",
  author: ""
})

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(10)
const bookDialogVisible = ref(false)  // 控制弹窗显示
const currentBook = ref<any>(null)  // 当前书籍信息
const upBookDrawer = ref(false) //控制编辑图书弹窗显示
const upCurrentBook = ref<any>(null)

// 获取图书列表
const getBooksList = () => {
  getBookPage(getPageUsersFileData.value)
      .then(response => {
        console.log('API Response:', response);  // 确保打印出整个响应对象
        if (response.data && response.data.results) {
          tableData.value = response.data.results;  // 更新表格数据
          total.value = response.data.total;        // 更新总数
        } else {
          ElMessage.error('返回的数据结构不正确');
        }
      })
};

onMounted(() => {
  getBooksList()
})

// 每页条数发生变化
const handleSizeChange = (val: number) => {
  getPageUsersFileData.value.pageSize = val
  getBooksList()  // 每次修改页大小时重新加载数据
  console.log(`${val} items per page`)
}

// 当前页码发生变化
const handleCurrentChange = (val: number) => {
  getPageUsersFileData.value.pageNumber = val
  getBooksList()  // 每次修改页码时重新加载数据
  console.log(`current page: ${val}`)
}

// 处理表格行点击事件
const handleRowClick = (row: any) => {
  currentBook.value = row
  bookDialogVisible.value = true
}

// 提交搜索
const onSubmit = () => {
  getPageUsersFileData.value.title = title.value
  getPageUsersFileData.value.author = author.value
  getBooksList()
}

// 清空输入框
const onSubmitEmpty = () => {
  getPageUsersFileData.value.title = ''
  getPageUsersFileData.value.author = ''
  title.value = ''
  author.value = ''
  getBooksList()  // 清空后重新加载数据
}

const title = ref('')
const author = ref('')

//修改图书信息
const editForm = ref({}); // 用于保存副本的数据

const upDataBook = (data) => {
  upBookDrawer.value = true
  upCurrentBook.value = data
  editForm.value = {...data}; // 创建副本
  state.value = data.categoryName
}

//图书编辑的提交函数
const upBookButton = () => {
  editForm.value.categoryName = state.value
  upBook(editForm.value)
  ElMessage.success("图书信息修改成功")
  upCurrentBook.value = false
  getBooksList()
}

//关闭抽屉
const cancelEdit = () => {
  upCurrentBook.value = false; // 关闭抽屉
  editForm.value = {}; // 清空副本
};


// 图书分类类型
interface RestaurantItem {
  value: string; // 显示的分类名称
  link: string;  // 分类的 ID
}

const state = ref('');
const restaurants = ref<RestaurantItem[]>([]);

const querySearch = (queryString: string, cb: (results: RestaurantItem[]) => void) => {
  const results = queryString
      ? restaurants.value.filter(createFilter(queryString))
      : restaurants.value;
  cb(results);
};

const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return restaurant.value.toLowerCase().includes(queryString.toLowerCase());
  };
};

const loadAll = async () => {
  try {
    const response = await getCategories();
    restaurants.value = response.data.map((item: any) => ({
      value: item.categoryName, // 用于显示分类名称
      link: item.categoryId,   // 分类 ID
    }));
  } catch (error) {
    console.error('Failed to load categories:', error);
    restaurants.value = [];
  }
};

const handleSelect = (item: RestaurantItem) => {
  state.value = item.value; // 选择后绑定分类名称
};

onMounted(() => {
  loadAll();
});

//时间选择器
const size = ref<'default' | 'large' | 'small'>('default')

//删除图书
const deleteBookDialogVisible = ref(false)
const deleteBookID = ref({
  bookId: ''
})
const deleteBookButton = (data) => {
  deleteBookDialogVisible.value = true
  deleteBookID.value.bookId = data.bookId;
}

const delBook = async () => {
  console.log(deleteBookID.value)
  await deleteBook(deleteBookID.value)
  deleteBookDialogVisible.value = false
  getBooksList()
  ElMessage.success("图书删除成功")
}

const adminToken = adminTokenStore()

const saveBookDrawer = ref(false)

const saveBookDTO = ref({
  title: '',
  author: '',
  categoryName: '',
  publishDate: '',
  stockQuantity: '',
  description: '',
  coverImage: '',
  wordCount: ''
})

//图片上传成功回调函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  saveBookDTO.value.coverImage = URL.createObjectURL(uploadFile.raw!)
}

//图片上传相关限制（类型和大小）
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须为JPG格式！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

//新增图书的接口调用
const saveBooks = async () => {
  saveBookDTO.value.coverImage = saveBookDTO.value.coverImage.split("blob:")[1]
  await saveBook(saveBookDTO.value)
  getBooksList()
  saveBookDrawer.value = false
  ElMessage.success("图书新增成功")
}

//关闭新增抽屉的回调函数
const saveBookHandleClose = () => {
  saveBookDrawer.value = false
  saveBookDTO.value.title = ''
  saveBookDTO.value.author = ''
  saveBookDTO.value.categoryName = ''
  saveBookDTO.value.publishDate = ''
  saveBookDTO.value.stockQuantity = ''
  saveBookDTO.value.description = ''
  saveBookDTO.value.coverImage = ''
  saveBookDTO.value.wordCount = ''
}

</script>


<template>
  <!-- 图书列表 -->
  <el-card>
    <div class="card-header">
      <span>图书管理</span>
      <el-button type="primary" @click="saveBookDrawer = true">
        新增图书
        <el-icon class="el-icon--right">
          <Upload/>
        </el-icon>
      </el-button>
    </div>
    <el-divider/>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="title" style="width: 240px" placeholder="请输入书名"/>
      </el-form-item>
      <el-form-item>
        <el-input v-model="author" style="width: 240px" placeholder="请输入作者名"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitEmpty">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%" @row-click="handleRowClick">
      <el-table-column prop="coverImage" label="图书封面">
        <template #default="{ row }">
          <div class="block">
            <el-image style="width: 72px; height: 96px" :src="row.coverImage"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="书名"/>
      <el-table-column prop="author" label="作者"/>
      <el-table-column prop="categoryName" label="分类"/>
      <el-table-column prop="publishDate" label="完结日期" :formatter="formatPublishDate"/>
      <el-table-column prop="popularityScore" label="书籍热度"/>
      <el-table-column prop="wordCount" label="书籍字数（万）"/>
      <el-table-column prop="createdAt" label="操作" width="180">
        <template #default="{row}">
          <div>
            <el-button type="primary" plain @click.stop="upDataBook(row)">编辑</el-button>
            <el-button type="danger" plain @click.stop="deleteBookButton(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
          class="el-p"
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 15, 20, 25]"
          layout="jumper, total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 图书详情弹窗 -->
  <el-dialog
      v-model="bookDialogVisible"
      :title="currentBook ? currentBook.title : '书籍详情'"
      width="500px"
  >
    <div v-if="currentBook">
      <div class="image-container">
        <el-image style="width: 216px; height: 288px" :src="currentBook.coverImage" alt="书籍封面"/>
      </div>
      <p><strong>作者:</strong> {{ currentBook.author }}</p>
      <p><strong>分类:</strong> {{ currentBook.categoryName }}</p>
      <p><strong>简介:</strong> <span v-html="currentBook.description"></span></p>
      <p><strong>字数:</strong> {{ currentBook.wordCount }} 万字</p>
      <p><strong>完结日期:</strong> {{ formatPublishDate(currentBook) }}</p>
    </div>
  </el-dialog>

  <!-- 图书编辑抽屉 -->
  <el-drawer
      v-model="upCurrentBook"
      size="40%"
      title="编辑图书"
      :before-close="cancelEdit"
  >
    <div v-if="upCurrentBook">
      <div class="image-container">
        <el-image style="width: 108px; height: 144px" :src="upCurrentBook.coverImage" alt="书籍封面"/>
      </div>
      <el-form :model="editForm" label-width="auto" style="max-width: 600px" label-position="left">
        <el-form-item label="书名">
          <el-input v-model="editForm.title"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="editForm.author"/>
        </el-form-item>
        <el-form-item label="图书分类">
          <div class="flex gap-4">
            <div>
              <!-- 自动完成输入框，绑定 state1，触发 querySearch 获取建议 -->
              <el-autocomplete
                  v-model="state"
                  :fetch-suggestions="querySearch"
                  clearable
                  class="inline-input w-50"
                  placeholder="Please Input"
                  @select="handleSelect"
              >
                <template #default="{ item }">
                  <div class="value">{{ item.value }}</div>
                </template>
              </el-autocomplete>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="完结日期">
          <div class="block">
            <el-date-picker
                v-model="editForm.publishDate"
                type="date"
                placeholder="Pick a day"
                :size="size"
            />
          </div>
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model="editForm.stockQuantity"/>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
              v-model="editForm.description"
              autosize
              type="textarea"
              placeholder="Please input"
          />
        </el-form-item>
        <el-form-item label="字数（万字）">
          <el-input v-model="editForm.wordCount"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="upBookButton">提交</el-button>
          <el-button type="danger" @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>

  <!-- 图书删除提示弹窗 -->
  <el-dialog
      v-model="deleteBookDialogVisible"
      title="删除图书提示"
      width="500"
  >
    <span>您确认要删除图书吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteBookDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="delBook">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 图书新增抽屉 -->
  <el-drawer
      v-model="saveBookDrawer"
      size="45%"
      title="图书新增"
      :before-close="saveBookHandleClose"
  >
    <el-form :model="saveBookDTO" label-width="auto" style="max-width: 600px">
      <el-form-item label="书名">
        <el-input v-model="saveBookDTO.title"/>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="saveBookDTO.author"/>
      </el-form-item>
      <el-form-item label="图书封面">
        <el-upload
            class="avatar-uploader"
            action="/api/common/upload"
            :headers="{'token': adminToken.token}"
            method="post"
            drag
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="saveBookDTO.coverImage" :src="saveBookDTO.coverImage" class="avatar"/>
          <div v-else class="upload-placeholder">
            <el-icon class="upload-icon"><Plus /></el-icon>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="图书分类">
        <div class="flex gap-4">
          <div>
            <!-- 自动完成输入框，触发 querySearch 获取建议 -->
            <el-autocomplete
                v-model="saveBookDTO.categoryName"
                :fetch-suggestions="querySearch"
                clearable
                class="inline-input w-50"
                placeholder="Please Input"
                @select="handleSelect"
            >
              <template #default="{ item }">
                <div class="value">{{ item.value }}</div>
              </template>
            </el-autocomplete>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="完结日期">
        <div class="block">
          <el-date-picker
              v-model="saveBookDTO.publishDate"
              type="date"
              placeholder="Pick a day"
              :size="size"
          />
        </div>
      </el-form-item>
      <el-form-item label="库存数量">
        <el-input v-model="saveBookDTO.stockQuantity"/>
      </el-form-item>
      <el-form-item label="简介">
        <el-input
            v-model="saveBookDTO.description"
            autosize
            type="textarea"
            placeholder="Please input"
        />
      </el-form-item>
      <el-form-item label="字数（万字）">
        <el-input v-model="saveBookDTO.wordCount"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveBooks">提交</el-button>
        <el-button type="danger" @click="saveBookDrawer = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>

</template>

<style scoped>
.el-p {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
}

.image-container {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
  width: 144px;
  height: 192px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
  background-color: #f0f7ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-uploader .el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: var(--el-text-color-secondary);
  text-align: center;
  transition: all 0.3s;
}

.avatar-uploader:hover .avatar-uploader-icon {
  color: var(--el-color-primary);
  transform: scale(1.1);
}

.avatar {
  width: 144px;
  height: 192px;
  display: block;
  object-fit: cover;
}

.el-upload--text {
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-icon.avatar-uploader-icon {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 32px;
}

.avatar-uploader .el-icon.avatar-uploader-icon::after {
  content: '点击上传封面';
  font-size: 14px;
  margin-top: 8px;
  color: var(--el-text-color-secondary);
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-bg-color);
}

.upload-icon {
  font-size: 40px;
  color: #dcdfe6;
}

.avatar {
  width: 144px;
  height: 192px;
  display: block;
  object-fit: cover;
}

</style>